package org.jumuning.redis.listener;

import org.jumuning.redis.handler.RedisMessageHandler;
import org.jumuning.redis.model.MessagesData;
import org.jumuning.redis.util.JacksonUtil;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.ObjectUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Redis 消息监听器，将接收到的消息反序列化为 DataVO，并委托给 RedisMessageHandler 处理
 */
public class RedisMessageListener implements MessageListener {

    private static final Logger log = LoggerFactory.getLogger(RedisMessageListener.class);

    private final StringRedisTemplate stringRedisTemplate;
    private final RedisMessageHandler<MessagesData> messageHandler;
    private final String channelName;

    public RedisMessageListener(StringRedisTemplate stringRedisTemplate,
                                RedisMessageHandler<MessagesData> messageHandler,
                                String channelName) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.messageHandler = messageHandler;
        this.channelName = channelName;
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            RedisSerializer<String> serializer = stringRedisTemplate.getStringSerializer();
            String channel = serializer.deserialize(message.getChannel());
            if (channelName.equals(channel)) {
                String body = serializer.deserialize(message.getBody());
                if (!ObjectUtils.isEmpty(body)) {
                    try {
                        MessagesData data = JacksonUtil.parseObject(body, MessagesData.class);
                        messageHandler.handleMessage(data);
                    } catch (Exception ex) {
                        log.error("parse or handle message error, body={}", body, ex);
                    }
                }
            }
        } catch (Exception e) {
            log.error("onMessage error", e);
        }
    }
}

